<template>
  <div class="contentView" :style="`height: ${contentHeight}px`">
    <div class="routeHeader">
      <el-button
        type="primary"
        @click="save"
        :loading="loading"
        v-hasPermi="['order:sales-material-management:save']"
      >
        保存
      </el-button>
      <el-button
        type="primary"
        @click="handle"
        :loading="loading"
        v-hasPermi="['order:sales-material-management:handle']"
      >
        提交
      </el-button>
      <el-button
        @click="goBack"
      >
        返回
      </el-button>
    </div>
    <el-scrollbar :max-height="`${contentHeight}px`">
      <el-table border v-loading="loading" :data="orderList">
        <el-table-column label="订单号" align="left" prop="orderNumber"  min-width="200px" />
        <el-table-column label="订单类型" align="left" prop="dictOrderType"  min-width="200px">
          <template #default="scope">
            <dict-tag type="market_order_type" :value="scope.row.dictOrderType" />
          </template>
        </el-table-column>
        <el-table-column label="业务类型" align="left" prop="dictBusinessType"  min-width="200px" >
          <template #default="scope">
            <dict-tag type="business_type" :value="scope.row.dictBusinessType" />
          </template>
        </el-table-column>
        <el-table-column label="销售类型" align="left" prop="dictSaleType"  min-width="200px" >
          <template #default="scope">
            <dict-tag type="sale_type" :value="scope.row.dictSaleType" />
          </template>
        </el-table-column>
        <el-table-column label="客户名称" align="left" prop="customerName"  min-width="200px" />
        <el-table-column label="客户代码" align="left" prop="customerCode"  min-width="200px" />
        <el-table-column label="销售部门" align="left" prop="salesDepartment"  min-width="200px" />
        <el-table-column label="合同日期" align="left" prop="contractDate"  min-width="200px" />
        <el-table-column label="订单日期" align="left" prop="orderDate"  min-width="200px" />
        <el-table-column label="业务员" align="left" prop="salesperson"  min-width="200px" />
        <el-table-column label="税率" align="left" prop="taxRate"  min-width="200px" />
        <el-table-column label="汇率" align="left" prop="exchangeRate"  min-width="200px" />
        <el-table-column label="付款条件" align="left" prop="paymentConditions"  min-width="200px" />
        <el-table-column label="变更类型" align="left" prop="dictChangeType"  min-width="200px" >
          <template #default="scope">
            <dict-tag type="change_type" :value="scope.row.dictChangeType" />
          </template>
        </el-table-column>
        <el-table-column label="商务合同" align="left" prop="fileName"  min-width="200px" >
          <template #default="scope">
            <div style="cursor: pointer;" @click="openFile(scope.row.filePath)">{{ scope.row.fileName }}</div>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="left" prop="remark"  min-width="200px" />
        <el-table-column label="创建人" align="left" prop="creatorName"  min-width="200px" />
        <el-table-column label="创建时间" align="left" prop="createTime"  min-width="200px" >
          <template #default="scope">
          <div>
            {{ formatDate(scope.row.createTime) }}
          </div>
        </template>
      </el-table-column>
        <el-table-column label="变更人" align="left" prop="orderChangePerson"  min-width="200px" />
        <el-table-column label="变更时间" align="left" prop="orderChangeDate"  min-width="200px" />
      </el-table>
      <div class="title">产品信息</div>
      <el-table border v-loading="loading" :data="productList">
        <el-table-column label="序号" type="index" fixed="left" />
        <el-table-column label="产品编号" align="left" prop="productNumber" width="240px">
          <template #default="scope">
            <div class="select-wrapper">
              <el-select
                v-model="scope.row.productNumber"
                placeholder="请选择产品编号"
                class="!w-240px"
                filterable
                remote
                :remote-method="filterOptions1"
              >
                <el-option
                  v-for="channel in filteredOptions1"
                  :key="channel.productNumber"
                  :value="channel.productNumber"
                  :label="channel.productNumber"
                />
              </el-select>
              <span class="search-icon" @click="handleSearch(scope.$index)">
                <Icon icon="ep:search" />
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="产品名称" align="left" prop="productName"  min-width="200px" />
        <el-table-column label="产品规格" align="left" prop="productStandard"  min-width="200px" />
        <el-table-column label="单位" align="left" prop="partUnit"  min-width="200px" />
        <el-table-column label="订单数量" align="left" prop="orderQuantity"  min-width="200px" />
        <el-table-column label="发货日期" align="left" prop="deliveryDate"  min-width="200px" />
        <el-table-column label="状态" align="left" prop="dictStatus"  min-width="200px" >
          <template #default="scope">
            <dict-tag type="market_order_status" :value="scope.row.dictStatus" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="left" prop="remark"  min-width="200px" />
      </el-table>
    </el-scrollbar>
  </div>
  <!-- 产品档案列表 -->
  <CustomerProfile ref="formRef" @success="addData" />
</template>
<script setup lang="ts">
import * as productRelationApi from '@/api/orderManagement/productRelation'
import * as SalesMaterialManagementApi from '@/api/orderManagement/salesMaterialManagement'
import { formatDate } from '@/utils/formatTime'
import { useTagsViewStore } from '@/store/modules/tagsView'
import CustomerProfile from './customerProfile.vue'
const { currentRoute, back } = useRouter()
let filteredOptions1 = ref<any>([])
const message = useMessage() // 消息弹窗
const tenantOptions = ref<any>([])
const loading = ref(false)  //数据加载中
const allInfo = reactive({
  info: {}
})
const orderList = ref<any>([])   //订单信息
const productList = ref([])   //产品信息
const contentHeight = ref(0)
//模糊查询
const filterOptions1 = async (query) => {
  if (query) {
    filteredOptions1 = await tenantOptions.value.filter((option) =>
      option.productNumber.includes(query)
    )
  }
}
//获取客户档案列表
const getProductsList = async () => {
  let params = {}
  const data = await productRelationApi.getProductsList(params)
  tenantOptions.value = data.list
}
//搜索图标
const formRef = ref()
const handleSearch = async (index) => {
  formRef.value.open(index, productList.value[index].productNumber)
}
const addData = async (data) => {
  console.log(data)
  productList.value[data.index.value].productNumber = data.list[0].productNumber
  productList.value[data.index.value].productName = data.list[0].productName
  productList.value[data.index.value].productStandard = data.list[0].productStandard
  productList.value[data.index.value].partUnit = data.list[0].partUnit
  console.log(productList.value[data.index.value])
}
// 返回
const tagsViewStore = useTagsViewStore()
const goBack = () => {
  //获取当前路由并删除tagView
  tagsViewStore.delView(currentRoute.value)
  back()
}

/** 初始化 */
const getData = async (id: any) => {
  loading.value = true
  try {
    const res = await SalesMaterialManagementApi.getSalesMaterialManagement(id)
    allInfo.info = res
    orderList.value = res.marketingOrderInfoRespVOS
    productList.value = res.productRelationRespVOS
  } finally {
    loading.value = false
  }
}

const openFile = (path: string) => {
  window.open(path)
}

// 保存
const save = () => {
  submitForm(10)
}

// 提交
const handle = () => {
  submitForm(20)
}

/** 提交表单 */
const submitForm = async (status: number) => {
  for (let i = 0; i < productList.value.length; i++) {
    if (!productList.value[i]['productNumber']) {
      message.error('请输入产品编号')
      return
    }
  }
  const data = allInfo.info
  data['dictSalesStatus'] = status
  data['productRelationUpdateReqVOS'] = productList.value
  loading.value = true
  try {
    await SalesMaterialManagementApi.updateSalesMaterialManagement(data)
    message.success('操作成功')
    back()
  } finally {
    loading.value = false
  }
}

/** 初始化 **/
onMounted(async () => {
  contentHeight.value = document.body.clientHeight - 125
  getData(currentRoute.value.query.id)
  await getProductsList()
})

</script>
<style lang="scss" scoped>
:deep(.el-scrollbar) {
  height: auto;
}

.btnWrap {
  margin-bottom: 10px;
}

.title {
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0;
}
.select-wrapper {
  display: flex;
  align-items: center;
}

.search-icon {
  margin-left: -24px; /* 这里的 -24px 是根据 Icon 的宽度进行调整的 */
  cursor: pointer;
  margin-top: 5px;
}
</style>
